#include"TcpServer.hpp"
#include"Socket.hpp"
#include"Protocol.hpp"

void Usage(std::string proc)
{
    std::cerr << "Usage: " << proc << " server_ip server_port" << std::endl;
}

void GetDataFromStdin(int *x,int* y,char* oper)
{
    std::cout<< "Please enter x # "<<std::endl;
    std::cin>>*x;
    std::cout<< "Please enter y # "<<std::endl;
    std::cin>>*y;
    std::cout<< "Please enter oper # "<<std::endl;
    std::cin>>*oper;
}

int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    // int n = socket(AF_INET,SOCK_STREAM,0);//这里就不用这样写了
    std::shared_ptr<Socket> client = std::make_shared<TcpSocket>();
    client->BuildTcpClientSocketMethod();
    if(client->Connect(server_ip,server_port)!=0)
    {
        std::cout<<"connect error"<<std::endl;
        exit(CONNECT_ERR);
    }
    //到这里是连接服务器成功
    std::unique_ptr<Protocol> protocol = std::make_unique<Protocol>();
    std::string resp_buffer;

    while(true)
    {
        //1.从标准输入获取
        int x,y;
        char oper;
        GetDataFromStdin(&x,&y,&oper);
        //2.构建请求，可以直接发送的字符串
        std::string req_str = protocol->BuildRequestString(x,y,oper);
        std::cout<<"----------req_str string---------------"<<std::endl;
        std::cout<<req_str;
        std::cout<<"----------------------------------------"<<std::endl;
        //3.发送请求
        client->Send(req_str);
        //4.获取应答
        Response resp;
        bool res = protocol->GetResponse(client,resp_buffer,&resp);
        if(!res)
        {
            break;
        }
        //5.显示结果
        //resp.ShowResult();
    }
    client->Close();
    return 0;
}